package com.ruoyi.system.type_handler;

import com.alibaba.fastjson2.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

public class ListTypeHandler extends BaseTypeHandler<List> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSON.toJSONString(parameter));
    }

    @Override
    public List getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return StringUtils.isNotEmpty(rs.getString(columnName)) ? JSON.parseArray(rs.getString(columnName), String.class) : Collections.emptyList();
    }

    @Override
    public List getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return StringUtils.isNotEmpty(rs.getString(columnIndex)) ? JSON.parseArray(rs.getString(columnIndex), String.class) : Collections.emptyList();
    }

    @Override
    public List getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return StringUtils.isNotEmpty(cs.getString(columnIndex)) ? JSON.parseArray(cs.getString(columnIndex), String.class) : Collections.emptyList();
    }
}
